'''
项目相关的API路由
'''
from flask import Blueprint, request, jsonify, g, current_app
from psycopg2.extras import RealDictCursor
from services.auth_service import login_required, tenant_required
import psycopg2
import time

# 创建蓝图
project_bp = Blueprint('project', __name__)

@project_bp.before_request
def log_request_info():
    print(f"[项目API] 收到请求: {request.method} {request.path}")
    print(f"[项目API] 请求头: {dict(request.headers)}")
    if request.is_json:
        print(f"[项目API] 请求数据: {request.get_json()}")

# 获取所有项目
@project_bp.route('/projects', methods=['GET'])
@login_required
def get_projects():
    try:
        print(f"[项目API] 用户 {g.current_user.get('username', '未知')} 请求获取项目列表")
        print(f"[项目API] 当前用户详情: {g.current_user}")
        conn = g.db
        cursor = conn.cursor(cursor_factory=RealDictCursor)
        
        # 获取用户的租户ID和用户ID
        tenant_id = g.current_user.get('tenant_id')
        user_id = g.current_user.get('user_id')
        
        if not tenant_id:
            print(f"[项目API错误] 未找到用户租户ID")
            return jsonify({
                'status': 'error',
                'message': '用户租户信息无效',
                'error_detail': '未能获取有效的租户ID，请重新登录'
            }), 400
            
        print(f"[项目API] 用户租户ID: {tenant_id}, 用户ID: {user_id}")
        
        # 直接使用一个更高效的单一查询获取项目列表
        # 使用单一SQL查询获取所有符合条件的项目
        cursor.execute('''
        SELECT DISTINCT p.* FROM projects p
        LEFT JOIN project_members pm ON p.id = pm.project_id
        WHERE p.tenant_id = %s 
        AND (
            p.creator_id = %s 
            OR p.owner_id = %s 
            OR (pm.user_id = %s AND pm.project_id IS NOT NULL)
        )
        AND p.status != 'deleted'
        ORDER BY p.created_at DESC
        ''', (tenant_id, user_id, user_id, user_id))
        
        projects = cursor.fetchall()
        project_count = len(projects)
        print(f"[项目API] 查询到 {project_count} 个项目")
            
        if len(projects) == 0:
            print("[项目API] 未找到项目，尝试自动修复数据...")
            # 尝试自动修复
            sync_project_members_all()
                
            # 再次查询所有项目
            cursor.execute('''
            SELECT DISTINCT p.* FROM projects p
            LEFT JOIN project_members pm ON p.id = pm.project_id
            WHERE p.tenant_id = %s 
            AND (
                p.creator_id = %s 
                OR p.owner_id = %s 
                OR (pm.user_id = %s AND pm.project_id IS NOT NULL)
            )
            AND p.status != 'deleted'
            ORDER BY p.created_at DESC
            ''', (tenant_id, user_id, user_id, user_id))
                
            projects = cursor.fetchall()
            print(f"[项目API] 修复后找到项目数量: {len(projects)}个")
        
        # 格式化日期时间字段为ISO格式字符串
        for project in projects:
            if 'created_at' in project and project['created_at']:
                project['created_at'] = project['created_at'].isoformat()
            if 'updated_at' in project and project['updated_at']:
                project['updated_at'] = project['updated_at'].isoformat()
        
        return jsonify({
            'status': 'success',
            'data': projects
        })
    except Exception as e:
        print(f"[项目API] 获取项目列表时出错: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'获取项目列表失败: {str(e)}'
        }), 500

# 创建新项目
@project_bp.route('/projects', methods=['POST'])
@login_required
def create_project():
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    name = data.get('name')
    description = data.get('description', '')
    
    if not name:
        return jsonify({
            'status': 'error',
            'message': '项目名称不能为空'
        }), 400
    
    # 获取用户的租户ID和用户ID
    tenant_id = g.current_user['tenant_id']
    user_id = g.current_user['user_id']
    
    # 获取Git仓库信息
    git_repository_url = data.get('git_repository_url')
    git_username = data.get('git_username')
    git_password = data.get('git_password')
    git_branch = data.get('git_branch', 'main')
    
    # 获取项目文件夹和数据库连接信息
    project_folder_path = data.get('project_folder_path')
    db_type = data.get('db_type')
    db_host = data.get('db_host')
    db_port = data.get('db_port')
    db_name = data.get('db_name')
    db_username = data.get('db_username')
    db_password = data.get('db_password')
    db_schema = data.get('db_schema', 'public')
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        # 创建项目，记录创建者和负责人，包括新增的字段
        cursor.execute('''
        INSERT INTO projects (
            name, description, tenant_id, creator_id, owner_id,
            git_repository_url, git_username, git_password, git_branch,
            project_folder_path, db_type, db_host, db_port, db_name, 
            db_username, db_password, db_schema
        )
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        RETURNING *
        ''', (
            name, description, tenant_id, user_id, user_id,
            git_repository_url, git_username, git_password, git_branch,
            project_folder_path, db_type, db_host, db_port, db_name,
            db_username, db_password, db_schema
        ))
        
        new_project = cursor.fetchone()
        project_id = new_project['id']
        
        # 将创建者添加为项目成员（负责人）
        cursor.execute('''
        INSERT INTO project_members (project_id, user_id, role)
        VALUES (%s, %s, %s)
        ''', (project_id, user_id, 'owner'))
        
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '项目创建成功',
            'data': new_project
        }), 201
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'创建项目失败: {str(e)}'
        }), 500

# 获取项目详情
@project_bp.route('/projects/<int:project_id>', methods=['GET'])
@login_required
def get_project(project_id):
    # 获取当前用户ID
    user_id = g.current_user['user_id']
    
    # 同步项目成员，确保数据一致性
    sync_project_members(project_id)
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 检查用户是否有权限访问该项目
    if not is_project_member(project_id, user_id):
        return jsonify({
            'status': 'error',
            'message': '没有访问此项目的权限'
        }), 403
    
    cursor.execute('''
    SELECT p.*, 
           CASE WHEN p.creator_id = %s THEN true ELSE false END as is_creator,
           CASE WHEN p.owner_id = %s THEN true ELSE false END as is_owner,
           c.username as creator_username,
           o.username as owner_username
    FROM projects p
    LEFT JOIN users c ON p.creator_id = c.id
    LEFT JOIN users o ON p.owner_id = o.id
    WHERE p.id = %s
    ''', (user_id, user_id, project_id))
    
    project = cursor.fetchone()
    
    if not project:
        return jsonify({
            'status': 'error',
            'message': '项目不存在'
        }), 404
    
    # 查询项目成员数量
    cursor.execute('''
    SELECT COUNT(*) AS member_count FROM project_members WHERE project_id = %s
    ''', (project_id,))
    member_count = cursor.fetchone()['member_count']
    
    # 添加项目成员数量信息
    project['member_count'] = member_count
    
    # 获取用户在项目中的角色
    cursor.execute('''
    SELECT role FROM project_members WHERE project_id = %s AND user_id = %s
    ''', (project_id, user_id))
    role_result = cursor.fetchone()
    
    if role_result:
        project['user_role'] = role_result['role']
    elif project['creator_id'] == user_id:
        project['user_role'] = 'creator'
    elif project['owner_id'] == user_id:
        project['user_role'] = 'owner'
    else:
        project['user_role'] = 'viewer'
    
    # 设置是否可以编辑项目
    project['can_edit'] = (project['owner_id'] == user_id)
    
    return jsonify({
        'status': 'success',
        'data': project
    })

# 更新项目
@project_bp.route('/projects/<int:project_id>', methods=['PUT'])
@login_required
def update_project(project_id):
    # 获取当前用户ID
    user_id = g.current_user['user_id']
    
    print(f"[更新项目调试] 请求更新项目 {project_id}，用户ID: {user_id}")
    
    # 检查用户是否是项目负责人
    if not is_project_owner(project_id, user_id):
        print(f"[更新项目错误] 用户 {user_id} 不是项目 {project_id} 的负责人")
        return jsonify({
            'status': 'error',
            'message': '只有项目负责人可以编辑项目'
        }), 403
    
    data = request.json
    if not data:
        print("[更新项目错误] 请求数据为空")
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    print(f"[更新项目调试] 收到的请求数据: {data}")
    
    name = data.get('name')
    description = data.get('description')
    status = data.get('status')
    git_repository_url = data.get('git_repository_url')
    git_username = data.get('git_username')
    git_password = data.get('git_password')
    git_branch = data.get('git_branch')
    owner_id = data.get('owner_id')
    
    # 获取项目文件夹和数据库连接信息
    project_folder_path = data.get('project_folder_path')
    db_type = data.get('db_type')
    db_host = data.get('db_host')
    db_port = data.get('db_port')
    db_name = data.get('db_name')
    db_username = data.get('db_username')
    db_password = data.get('db_password')
    db_schema = data.get('db_schema')
    
    print(f"[更新项目调试] 项目文件夹路径: {project_folder_path}")
    print(f"[更新项目调试] 数据库信息: 类型={db_type}, 主机={db_host}, 端口={db_port}, 名称={db_name}, 用户名={db_username}")
    
    # 构建更新字段
    update_fields = []
    update_values = []
    
    if name:
        update_fields.append('name = %s')
        update_values.append(name)
    
    if description is not None:
        update_fields.append('description = %s')
        update_values.append(description)
    
    if status:
        update_fields.append('status = %s')
        update_values.append(status)
    
    if git_repository_url is not None:
        update_fields.append('git_repository_url = %s')
        update_values.append(git_repository_url)
    
    if git_username is not None:
        update_fields.append('git_username = %s')
        update_values.append(git_username)
    
    if git_password is not None:
        update_fields.append('git_password = %s')
        update_values.append(git_password)
    
    if git_branch is not None:
        update_fields.append('git_branch = %s')
        update_values.append(git_branch)
    
    if owner_id is not None:
        update_fields.append('owner_id = %s')
        update_values.append(owner_id)
    
    # 添加项目文件夹和数据库连接信息字段
    if project_folder_path is not None:
        update_fields.append('project_folder_path = %s')
        update_values.append(project_folder_path)
    
    if db_type is not None:
        update_fields.append('db_type = %s')
        update_values.append(db_type)
        
    if db_host is not None:
        update_fields.append('db_host = %s')
        update_values.append(db_host)
        
    if db_port is not None:
        update_fields.append('db_port = %s')
        update_values.append(db_port)
        
    if db_name is not None:
        update_fields.append('db_name = %s')
        update_values.append(db_name)
        
    if db_username is not None:
        update_fields.append('db_username = %s')
        update_values.append(db_username)
        
    if db_password is not None:
        update_fields.append('db_password = %s')
        update_values.append(db_password)
        
    if db_schema is not None:
        update_fields.append('db_schema = %s')
        update_values.append(db_schema)
    
    if not update_fields:
        return jsonify({
            'status': 'error',
            'message': '没有提供要更新的字段'
        }), 400
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        update_fields.append('updated_at = CURRENT_TIMESTAMP')
        
        query = f'''
        UPDATE projects 
        SET {', '.join(update_fields)}
        WHERE id = %s
        RETURNING *
        '''
        
        print(f"[更新项目调试] SQL查询: {query}")
        print(f"[更新项目调试] 参数值: {update_values}")
        
        update_values.append(project_id)
        cursor.execute(query, update_values)
        
        updated_project = cursor.fetchone()
        print(f"[更新项目调试] 更新后的项目数据: {updated_project}")
        
        # 如果更改了负责人，确保在项目成员表中也有记录
        if owner_id is not None and owner_id != updated_project['owner_id']:
            cursor.execute('''
            INSERT INTO project_members (project_id, user_id, role)
            VALUES (%s, %s, 'owner')
            ON CONFLICT (project_id, user_id) 
            DO UPDATE SET role = 'owner'
            ''', (project_id, owner_id))
        
        conn.commit()
        print(f"[更新项目调试] 项目 {project_id} 更新成功，已提交事务")
        
        return jsonify({
            'status': 'success',
            'message': '项目更新成功',
            'data': updated_project
        })
    
    except Exception as e:
        conn.rollback()
        print(f"[更新项目错误] 更新项目 {project_id} 失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'更新项目失败: {str(e)}'
        }), 500

# 删除项目
@project_bp.route('/projects/<int:project_id>', methods=['DELETE'])
@login_required
@tenant_required
def delete_project(project_id):
    conn = g.db
    cursor = conn.cursor()
    
    try:
        # 租户检查已在tenant_required装饰器中完成
        
        # 获取项目信息
        cursor.execute('SELECT * FROM projects WHERE id = %s', (project_id,))
        project = cursor.fetchone()
        
        if not project:
            return jsonify({
                'status': 'error',
                'message': '项目不存在'
            }), 404
        
        # 标记为删除（软删除）而不是实际删除
        cursor.execute('''
        UPDATE projects 
        SET status = 'deleted', updated_at = CURRENT_TIMESTAMP
        WHERE id = %s
        ''', (project_id,))
        
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '项目已删除'
        })
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'删除项目失败: {str(e)}'
        }), 500

# 获取项目下的任务列表
@project_bp.route('/projects/<int:project_id>/tasks', methods=['GET'])
@login_required
def get_project_tasks(project_id):
    # 获取当前用户ID
    user_id = g.current_user['user_id']
    
    # 检查用户是否有权限访问该项目
    if not is_project_member(project_id, user_id):
        return jsonify({
            'status': 'error',
            'message': '没有访问此项目的权限'
        }), 403
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT * FROM main_tasks 
    WHERE project_id = %s
    ORDER BY created_at DESC
    ''', (project_id,))
    
    tasks = cursor.fetchall()
    
    # 格式化日期时间字段
    for task in tasks:
        if 'created_at' in task and task['created_at']:
            task['created_at'] = task['created_at'].isoformat()
        if 'updated_at' in task and task['updated_at']:
            task['updated_at'] = task['updated_at'].isoformat()
    
    return jsonify({
        'status': 'success',
        'data': tasks
    })

# 创建任务
@project_bp.route('/projects/<int:project_id>/tasks', methods=['POST'])
@login_required
def create_task(project_id):
    # 获取当前用户ID
    user_id = g.current_user['user_id']
    
    # 检查用户是否有权限访问该项目
    if not is_project_member(project_id, user_id):
        return jsonify({
            'status': 'error',
            'message': '没有访问此项目的权限'
        }), 403
    
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    title = data.get('title')
    description = data.get('description', '')
    
    if not title:
        return jsonify({
            'status': 'error',
            'message': '任务标题不能为空'
        }), 400
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        cursor.execute('''
        INSERT INTO main_tasks (project_id, title, description)
        VALUES (%s, %s, %s)
        RETURNING *
        ''', (project_id, title, description))
        
        new_task = cursor.fetchone()
        
        # 格式化日期时间字段
        if new_task:
            if 'created_at' in new_task and new_task['created_at']:
                new_task['created_at'] = new_task['created_at'].isoformat()
            if 'updated_at' in new_task and new_task['updated_at']:
                new_task['updated_at'] = new_task['updated_at'].isoformat()
        
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '任务创建成功',
            'data': new_task
        }), 201
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'创建任务失败: {str(e)}'
        }), 500

# 删除项目任务
@project_bp.route('/projects/<int:project_id>/tasks/<int:task_id>', methods=['DELETE'])
@login_required
@tenant_required
def delete_project_task(project_id, task_id):
    print(f"[删除任务] 开始删除项目 {project_id} 的任务 {task_id}")
    print(f"[删除任务] 当前用户: {g.current_user}")
    print(f"[删除任务] 当前租户: {g.current_user.get('tenant_id')}")
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        # 检查项目是否存在且属于当前租户
        cursor.execute('''
            SELECT * FROM projects 
            WHERE id = %s 
            AND tenant_id = %s 
            AND status != 'deleted'
        ''', (project_id, g.current_user.get('tenant_id')))
        project = cursor.fetchone()
        
        if not project:
            print(f"[删除任务] 项目 {project_id} 不存在、已被删除或不属于当前租户")
            return jsonify({
                'status': 'error',
                'message': '项目不存在或无权访问'
            }), 404
            
        # 检查任务是否存在且属于该项目
        cursor.execute('''
            SELECT * FROM main_tasks 
            WHERE id = %s 
            AND project_id = %s
        ''', (task_id, project_id))
        
        task = cursor.fetchone()
        
        if not task:
            print(f"[删除任务] 任务 {task_id} 不存在或不属于项目 {project_id}")
            return jsonify({
                'status': 'error',
                'message': '任务不存在或不属于该项目'
            }), 404
            
        print(f"[删除任务] 开始删除任务 {task_id} 的相关数据")
        print(f"[删除任务] 任务信息: {task}")
        
        try:
            # 开始事务
            # 删除任务相关的所有子任务
            cursor.execute('''
                DELETE FROM sub_tasks
                WHERE breakdown_version_id IN (
                    SELECT id FROM task_breakdown_versions
                    WHERE main_task_id = %s
                )
                RETURNING id
            ''', (task_id,))
            deleted_subtasks = cursor.fetchall()
            print(f"[删除任务] 已删除 {len(deleted_subtasks)} 个子任务")
            
            # 删除任务的所有拆分版本
            cursor.execute('''
                DELETE FROM task_breakdown_versions
                WHERE main_task_id = %s
                RETURNING id
            ''', (task_id,))
            deleted_versions = cursor.fetchall()
            print(f"[删除任务] 已删除 {len(deleted_versions)} 个拆分版本")
            
            # 删除主任务
            cursor.execute('''
                DELETE FROM main_tasks
                WHERE id = %s
                AND project_id = %s
                RETURNING id, title
            ''', (task_id, project_id))
            deleted_task = cursor.fetchone()
            
            if not deleted_task:
                raise Exception("无法删除主任务，可能已被删除或不存在")
                
            print(f"[删除任务] 主任务删除成功: {deleted_task}")
            
            # 提交事务
            conn.commit()
            print(f"[删除任务] 删除操作已成功提交到数据库")
            
            return jsonify({
                'status': 'success',
                'message': '任务已成功删除',
                'data': {
                    'task_id': deleted_task['id'],
                    'title': deleted_task['title']
                }
            })
            
        except Exception as e:
            # 回滚事务
            conn.rollback()
            print(f"[删除任务] 删除过程中发生错误: {str(e)}")
            raise
            
    except Exception as e:
        print(f"[删除任务] 发生错误: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'删除任务失败: {str(e)}'
        }), 500

# 检查用户是否是项目负责人
def is_project_owner(project_id, user_id):
    conn = g.db
    cursor = conn.cursor()
    
    cursor.execute('''
    SELECT 1 FROM projects 
    WHERE id = %s AND owner_id = %s
    ''', (project_id, user_id))
    
    return cursor.fetchone() is not None

# 检查用户是否是项目成员
def is_project_member(project_id, user_id):
    conn = g.db
    cursor = conn.cursor()
    
    print(f"[检查项目成员] 检查用户 {user_id} 是否为项目 {project_id} 的成员")
    
    cursor.execute('''
    SELECT 1 FROM project_members 
    WHERE project_id = %s AND user_id = %s
    UNION
    SELECT 1 FROM projects 
    WHERE id = %s AND (owner_id = %s OR creator_id = %s)
    ''', (project_id, user_id, project_id, user_id, user_id))
    
    result = cursor.fetchone() is not None
    print(f"[检查项目成员] 结果: {'是成员' if result else '不是成员'}")
    return result

# 获取项目成员列表
@project_bp.route('/projects/<int:project_id>/members', methods=['GET'])
@login_required
def get_project_members(project_id):
    # 获取当前用户ID
    user_id = g.current_user['user_id']
    
    # 同步项目成员，确保数据一致性
    sync_project_members(project_id)
    
    # 检查用户是否有权限访问该项目
    if not is_project_member(project_id, user_id):
        return jsonify({
            'status': 'error',
            'message': '没有访问此项目的权限'
        }), 403
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        # 获取项目成员（包括项目创建人和负责人）
        cursor.execute('''
        SELECT u.id, u.username, u.email, pm.role, pm.added_at, 
               CASE WHEN p.creator_id = u.id THEN true ELSE false END as is_creator,
               CASE WHEN p.owner_id = u.id THEN true ELSE false END as is_owner
        FROM users u
        LEFT JOIN project_members pm ON u.id = pm.user_id AND pm.project_id = %s
        LEFT JOIN projects p ON p.id = %s
        WHERE pm.project_id = %s 
           OR p.creator_id = u.id 
           OR p.owner_id = u.id
        ORDER BY pm.role, u.username
        ''', (project_id, project_id, project_id))
        
        members = cursor.fetchall()
        
        # 格式化日期
        for member in members:
            if 'added_at' in member and member['added_at']:
                member['added_at'] = member['added_at'].isoformat()
        
        return jsonify({
            'status': 'success',
            'data': members
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'获取项目成员失败: {str(e)}'
        }), 500

# 添加项目成员
@project_bp.route('/projects/<int:project_id>/members', methods=['POST'])
@login_required
def add_project_member(project_id):
    # 获取当前用户ID和租户ID
    user_id = g.current_user['user_id']
    tenant_id = g.current_user.get('tenant_id')
    
    print(f"[添加项目成员] 用户 {user_id} 尝试向项目 {project_id} 添加成员，当前租户: {tenant_id}")
    
    # 检查用户是否是项目负责人
    if not is_project_owner(project_id, user_id):
        print(f"[添加项目成员] 用户 {user_id} 不是项目 {project_id} 的负责人，无权添加成员")
        return jsonify({
            'status': 'error',
            'message': '只有项目负责人可以添加成员'
        }), 403
    
    data = request.json
    if not data:
        print(f"[添加项目成员] 请求数据为空")
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    member_id = data.get('user_id')
    role = data.get('role', 'member')
    
    print(f"[添加项目成员] 添加用户 {member_id} 到项目 {project_id}，角色: {role}")
    
    if not member_id:
        print(f"[添加项目成员] 用户ID为空")
        return jsonify({
            'status': 'error',
            'message': '用户ID不能为空'
        }), 400
    
    if role not in ['member', 'manager', 'owner']:
        print(f"[添加项目成员] 无效的角色: {role}")
        return jsonify({
            'status': 'error',
            'message': '无效的角色类型'
        }), 400
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        # 检查用户是否存在并且属于同一租户
        cursor.execute('SELECT id, tenant_id, username FROM users WHERE id = %s', (member_id,))
        member = cursor.fetchone()
        
        if not member:
            print(f"[添加项目成员] 用户 {member_id} 不存在")
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
        
        print(f"[添加项目成员] 找到用户: {member['username']}，租户ID: {member['tenant_id']}")
        
        # 检查用户和项目的租户ID是否一致
        cursor.execute('SELECT tenant_id FROM projects WHERE id = %s', (project_id,))
        project = cursor.fetchone()
        
        if not project:
            print(f"[添加项目成员] 项目 {project_id} 不存在")
            return jsonify({
                'status': 'error',
                'message': '项目不存在'
            }), 404
        
        print(f"[添加项目成员] 项目 {project_id} 租户ID: {project['tenant_id']}")
        
        if member['tenant_id'] != project['tenant_id']:
            print(f"[添加项目成员] 租户不匹配: 用户租户 {member['tenant_id']} vs 项目租户 {project['tenant_id']}")
            return jsonify({
                'status': 'error',
                'message': '只能添加同一租户下的用户为项目成员'
            }), 403
        
        # 如果角色是owner，则更新项目负责人
        if role == 'owner':
            print(f"[添加项目成员] 设置用户 {member_id} 为项目 {project_id} 的负责人")
            cursor.execute('''
            UPDATE projects SET owner_id = %s WHERE id = %s
            ''', (member_id, project_id))
        
        # 检查成员是否已存在
        cursor.execute('SELECT id, role FROM project_members WHERE project_id = %s AND user_id = %s', 
                      (project_id, member_id))
        existing_member = cursor.fetchone()
        
        if existing_member:
            print(f"[添加项目成员] 用户 {member_id} 已经是项目 {project_id} 的成员，当前角色: {existing_member['role']}")
        
        # 添加或更新项目成员
        cursor.execute('''
        INSERT INTO project_members (project_id, user_id, role)
        VALUES (%s, %s, %s)
        ON CONFLICT (project_id, user_id) 
        DO UPDATE SET role = EXCLUDED.role
        RETURNING id, role
        ''', (project_id, member_id, role))
        
        result = cursor.fetchone()
        print(f"[添加项目成员] 操作结果: {result}")
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '项目成员添加成功',
            'data': result
        }), 201
    
    except Exception as e:
        conn.rollback()
        print(f"[添加项目成员] 错误: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'添加项目成员失败: {str(e)}'
        }), 500

# 删除项目成员
@project_bp.route('/projects/<int:project_id>/members/<int:member_id>', methods=['DELETE'])
@login_required
def remove_project_member(project_id, member_id):
    # 获取当前用户ID
    user_id = g.current_user['user_id']
    
    # 检查用户是否是项目负责人
    if not is_project_owner(project_id, user_id):
        return jsonify({
            'status': 'error',
            'message': '只有项目负责人可以删除成员'
        }), 403
    
    # 不能删除自己
    if member_id == user_id:
        return jsonify({
            'status': 'error',
            'message': '项目负责人不能移除自己'
        }), 400
    
    conn = g.db
    cursor = conn.cursor()
    
    try:
        # 检查要删除的用户是否是项目创建人
        cursor.execute('''
        SELECT creator_id FROM projects WHERE id = %s
        ''', (project_id,))
        result = cursor.fetchone()
        
        if result and result[0] == member_id:
            return jsonify({
                'status': 'error',
                'message': '不能删除项目创建人'
            }), 400
        
        # 删除项目成员
        cursor.execute('''
        DELETE FROM project_members
        WHERE project_id = %s AND user_id = %s
        RETURNING id
        ''', (project_id, member_id))
        
        result = cursor.fetchone()
        
        if not result:
            return jsonify({
                'status': 'error',
                'message': '该用户不是项目成员'
            }), 404
        
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '成员已从项目中移除'
        })
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'移除项目成员失败: {str(e)}'
        }), 500

# 同步项目成员，确保项目创建者和负责人都在项目成员表中
def sync_project_members(project_id):
    """确保项目创建者和负责人都被添加为项目成员"""
    try:
        conn = g.db
        cursor = conn.cursor(cursor_factory=RealDictCursor)
        
        print(f"[同步项目成员] 开始同步项目 {project_id} 的成员")
        
        # 获取项目信息
        cursor.execute('''
        SELECT creator_id, owner_id FROM projects WHERE id = %s
        ''', (project_id,))
        
        project = cursor.fetchone()
        if not project:
            print(f"[同步项目成员] 项目 {project_id} 不存在")
            return False
        
        print(f"[同步项目成员] 项目 {project_id} 信息: 创建者={project['creator_id']}, 负责人={project['owner_id']}")
        
        # 如果owner_id为空，将creator_id设置为owner_id
        if project['owner_id'] is None and project['creator_id'] is not None:
            print(f"[同步项目成员] 项目 {project_id} 负责人为空，设置为创建者 {project['creator_id']}")
            cursor.execute('''
            UPDATE projects SET owner_id = creator_id WHERE id = %s
            ''', (project_id,))
            project['owner_id'] = project['creator_id']
        
        # 确保创建者在项目成员表中
        if project['creator_id']:
            print(f"[同步项目成员] 添加创建者 {project['creator_id']} 到项目 {project_id} 成员表")
            cursor.execute('''
            INSERT INTO project_members (project_id, user_id, role)
            VALUES (%s, %s, 'creator')
            ON CONFLICT (project_id, user_id) DO NOTHING
            ''', (project_id, project['creator_id']))
        
        # 确保负责人在项目成员表中
        if project['owner_id'] and project['owner_id'] != project['creator_id']:
            print(f"[同步项目成员] 添加负责人 {project['owner_id']} 到项目 {project_id} 成员表")
            cursor.execute('''
            INSERT INTO project_members (project_id, user_id, role)
            VALUES (%s, %s, 'owner')
            ON CONFLICT (project_id, user_id) DO NOTHING
            ''', (project_id, project['owner_id']))
        
        conn.commit()
        print(f"[同步项目成员] 项目 {project_id} 成员同步完成")
        return True
    except Exception as e:
        print(f"[同步项目成员] 错误: {str(e)}")
        return False

# 同步所有项目成员（管理员API）
@project_bp.route('/admin/sync-project-members', methods=['POST'])
@login_required
def sync_all_project_members():
    # 验证当前用户是否为管理员
    if g.current_user.get('role') != 'admin':
        return jsonify({
            'status': 'error',
            'message': '只有管理员可以执行此操作'
        }), 403
    
    conn = g.db
    cursor = conn.cursor()
    
    try:
        # 获取所有项目ID
        cursor.execute('SELECT id FROM projects')
        projects = cursor.fetchall()
        
        success_count = 0
        for project in projects:
            project_id = project[0]
            if sync_project_members(project_id):
                success_count += 1
        
        return jsonify({
            'status': 'success',
            'message': f'成功同步 {success_count}/{len(projects)} 个项目的成员'
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'同步项目成员失败: {str(e)}'
        }), 500

# 更新所有现有项目的owner_id（管理员API）
@project_bp.route('/admin/update-project-owners', methods=['POST'])
@login_required
def update_all_project_owners():
    # 验证当前用户是否为管理员
    if g.current_user.get('role') != 'admin':
        return jsonify({
            'status': 'error',
            'message': '只有管理员可以执行此操作'
        }), 403
    
    conn = g.db
    cursor = conn.cursor()
    
    try:
        # 更新所有owner_id为空的项目
        cursor.execute('''
        UPDATE projects SET owner_id = creator_id 
        WHERE owner_id IS NULL AND creator_id IS NOT NULL
        ''')
        
        updated_count = cursor.rowcount
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': f'成功更新 {updated_count} 个项目的负责人'
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'更新项目负责人失败: {str(e)}'
        }), 500

# 同步所有项目成员，无需权限检查
def sync_project_members_all():
    """同步所有项目的成员关系，用于内部调用"""
    try:
        conn = g.db
        cursor = conn.cursor()
        
        # 获取所有项目ID
        cursor.execute('SELECT id FROM projects')
        projects = cursor.fetchall()
        
        # 更新所有owner_id为空的项目
        cursor.execute('''
        UPDATE projects SET owner_id = creator_id 
        WHERE owner_id IS NULL AND creator_id IS NOT NULL
        ''')
        
        for project in projects:
            project_id = project[0]
            sync_project_members(project_id)
        
        conn.commit()
        print(f"[同步项目] 已同步 {len(projects)} 个项目的成员关系")
        return True
    except Exception as e:
        conn.rollback()
        print(f"[同步项目错误] {str(e)}")
        return False

@project_bp.route('/admin/check-projects', methods=['GET'])
@login_required
def check_projects():
    """调试API：检查数据库中所有项目数据"""
    if g.current_user.get('role') != 'admin':
        return jsonify({
            'status': 'error',
            'message': '权限不足',
            'error_detail': '只有管理员可以访问此接口'
        }), 403
    
    try:
        conn = g.db
        cursor = conn.cursor(cursor_factory=RealDictCursor)
        
        # 获取全部项目
        cursor.execute('''
        SELECT * FROM projects WHERE status != 'deleted'
        ''')
        all_projects = cursor.fetchall()
        
        # 获取全部用户
        cursor.execute('''
        SELECT id, username, tenant_id, role FROM users
        ''')
        all_users = cursor.fetchall()
        
        # 获取项目成员表
        cursor.execute('''
        SELECT * FROM project_members
        ''')
        all_members = cursor.fetchall()
        
        # 检查creator_id和owner_id
        null_owner_count = 0
        for project in all_projects:
            if project['owner_id'] is None:
                null_owner_count += 1
                
        for project in all_projects:
            # 格式化日期时间字段为ISO格式字符串
            if 'created_at' in project and project['created_at']:
                project['created_at'] = project['created_at'].isoformat()
            if 'updated_at' in project and project['updated_at']:
                project['updated_at'] = project['updated_at'].isoformat()
        
        return jsonify({
            'status': 'success',
            'data': {
                'all_projects': all_projects,
                'all_users': all_users,
                'null_owner_count': null_owner_count,
                'project_count': len(all_projects),
                'user_count': len(all_users),
                'all_members': all_members
            }
        })
    except Exception as e:
        print(f"[检查项目数据错误] {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'获取项目数据失败: {str(e)}'
        }), 500

@project_bp.route('/admin/create-test-project', methods=['POST'])
@login_required
def create_test_project():
    """调试API：创建测试项目"""
    if g.current_user.get('role') != 'admin':
        return jsonify({
            'status': 'error',
            'message': '权限不足',
            'error_detail': '只有管理员可以访问此接口'
        }), 403
    
    try:
        conn = g.db
        cursor = conn.cursor(cursor_factory=RealDictCursor)
        
        # 获取当前管理员用户ID
        user_id = g.current_user.get('user_id')
        tenant_id = g.current_user.get('tenant_id')
        
        if not user_id or not tenant_id:
            return jsonify({
                'status': 'error',
                'message': '用户信息无效',
                'error_detail': '无法获取用户ID或租户ID'
            }), 400
        
        # 创建测试项目
        cursor.execute('''
        INSERT INTO projects 
        (name, description, tenant_id, creator_id, owner_id, status, created_at, updated_at) 
        VALUES 
        (%s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        RETURNING *
        ''', (
            f'测试项目-{int(time.time())}', 
            '这是一个自动创建的测试项目', 
            tenant_id,
            user_id,
            user_id,
            'active'
        ))
        
        new_project = cursor.fetchone()
        
        # 将创建者添加为项目成员
        if new_project:
            project_id = new_project['id']
            cursor.execute('''
            INSERT INTO project_members
            (project_id, user_id, role, added_at)
            VALUES
            (%s, %s, %s, CURRENT_TIMESTAMP)
            ON CONFLICT (project_id, user_id) DO NOTHING
            ''', (
                project_id,
                user_id,
                'owner'
            ))
        
        conn.commit()
        
        if 'created_at' in new_project and new_project['created_at']:
            new_project['created_at'] = new_project['created_at'].isoformat()
        if 'updated_at' in new_project and new_project['updated_at']:
            new_project['updated_at'] = new_project['updated_at'].isoformat()
        
        return jsonify({
            'status': 'success',
            'message': '测试项目创建成功',
            'data': new_project
        })
        
    except Exception as e:
        conn.rollback()
        print(f"[创建测试项目错误] {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'创建测试项目失败: {str(e)}'
        }), 500 